package com.hanbang.mrcm.home;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import com.hanbang.mrcm.R;
import com.hanbang.mrcm.adapter.BannerAdAdapter;
import com.hanbang.mrcm.base.BaseActivity;
import com.hanbang.mrcm.bean.ActivityDetailData;
import com.hanbang.mrcm.bean.BannerAdData;
import com.hanbang.mrcm.cdker_type.ResultActivity;
import com.hanbang.mrcm.merchant.ScantronActivity;
import com.hanbang.mrcm.merchant.SharedRankActivity;
import com.hanbang.mrcm.myview.MyDialog;
import com.hanbang.mrcm.myview.MyDialog.OnClickCallback;
import com.hanbang.mrcm.utils.HttpInterfaces;
import com.hanbang.mrcm.utils.JsonHelper;
import com.hanbang.mrcm.utils.MyLog;
import com.hanbang.mrcm.utils.MyRequestCallBack;
import com.hanbang.mrcm.utils.MyToast;
import com.hanbang.mrcm.utils.SystemTools;
import com.hanbang.mrcm.utils.UiUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class DetailActivity extends BaseActivity {
	private ActivityDetailData detailData = null;
	private PullToRefreshScrollView scrollView = null;
	private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<BannerAdData>();
	private BannerAdAdapter bannerAdAdapter = null;
	private WebView webview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail);
		initView();
		switchUi(getIntent().getIntExtra("type", -1));
		setOnClickListener();
		getServiceActivity();
		getTopData();
	}

	/*
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		ImageView iv = (ImageView) findViewById(R.id.phone_im);
		iv.setOnClickListener(onClickListener);
		UiUtils.setButtonClickTint(iv, R.color.red_shen, R.color.gray);
		findViewById(R.id.shangjia_ll).setOnClickListener(onClickListener);
		findViewById(R.id.get_type).setOnClickListener(onClickListener);
		findViewById(R.id.rank).setOnClickListener(onClickListener);
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.phone_im:
				callPhone();
				break;
			case R.id.shangjia_ll:
				if (detailData != null) {
					Intent intent = new Intent();
					intent.setClass(DetailActivity.this, GoodListActivity.class);
					intent.putExtra("trade_id", detailData.getTrade_id());
					startActivity(intent);
				}
				break;
			case R.id.get_type:
				getCdker(v);
				break;
			case R.id.rank:
				Intent intent = new Intent();
				intent.setClass(DetailActivity.this, SharedRankActivity.class);
				intent.putExtra("type", detailData.getType());
				intent.putExtra("activity_id", detailData.getActivity_id());
				startActivity(intent);
				break;
			case R.id.right_imageview:
				shared(false);
				break;
			default:
				break;
			}
		}
	};

	/*
	 * 领取兑换码
	 */
	private void getCdker(View v) {
		if (detailData != null) {
			if (!isLogin(true)) {
				return;
			}
			Intent intent = new Intent();
			switch (detailData.getType()) {
			// 直接领取
			case 0:
				intent.putExtra("type", detailData.getType());
				intent.putExtra("activity_id", detailData.getActivity_id());
				intent.setClass(this, ResultActivity.class);
				startActivity(intent);
				break;
			// 分享领取
			case 1:
				shared(true);
				break;
			// 答题领取
			case 2:
				if (v.getTag() != null && (Integer) v.getTag() == 2) {
					intent.putExtra("type", detailData.getType());
					intent.putExtra("activity_id", detailData.getActivity_id());
					intent.setClass(this, ResultActivity.class);
					startActivity(intent);
				} else {
					intent.setClass(DetailActivity.this, ScantronActivity.class);
					intent.putExtra("type", detailData.getType());
					intent.putExtra("activity_id", detailData.getActivity_id());
					startActivity(intent);
				}
				break;

			default:
				break;
			}
		}

	}

	/*
	 * 初始化view
	 */
	private void initView() {
		// 设置顶部的标题
		setBackArrows(findViewById(R.id.top_bar_left_image));
		setTitle(findViewById(R.id.top_bar_title), "兑换详情");

		ImageView imageView = (ImageView) findViewById(R.id.right_imageview);
		imageView.setImageResource(R.drawable.shared_top);
		imageView.setVisibility(View.VISIBLE);
		UiUtils.setButtonClickTint(imageView, R.color.white, R.color.gray_99);
		imageView.setOnClickListener(onClickListener);

		TextView tv = (TextView) findViewById(R.id.get_type);
		tv.setEnabled(false);
		tv.setText("领取");

		scrollView = (PullToRefreshScrollView) findViewById(R.id.scrollview);
		scrollView.setMode(Mode.PULL_FROM_START);
		scrollView.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				bannerAdDatas.clear();
				getServiceActivity();
				getTopData();

			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {

			}
		});

		bannerAdAdapter = new BannerAdAdapter(this,
				(RelativeLayout) findViewById(R.id.banner_ad), bannerAdDatas);
		bannerAdAdapter.setWidthAndHeight(16, 9);
		bannerAdAdapter.notifyDataSetChanged();

		webview = (WebView) findViewById(R.id.webview);
		configWebview();
	}

	/*
	 * 获取活动的详细信息
	 */
	private void getServiceActivity() {
		httpUtils.send(HttpMethod.GET, HttpInterfaces.getActivity
				+ "&activity_id=" + getIntent().getIntExtra("activity", -1),
				new MyRequestCallBack<String>(this,
						getString(R.string.loadding)) {
					@Override
					public void onFailure(HttpException error, String msg) {
						super.onFailure(error, msg);
						scrollView.onRefreshComplete();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								detailData = JsonHelper.parseObject(json
										.getJSONArray("result")
										.getJSONObject(0),
										ActivityDetailData.class);
								switchUi(detailData.getType());
								updataUi();
								/*
								 * 判断是否参加过这个活动
								 */
								isJoinActivity();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						scrollView.onRefreshComplete();
					}
				});
	}

	private void getTopData() {
		httpUtils.send(HttpMethod.GET, HttpInterfaces.goodPic + "&activity_id="
				+ getIntent().getIntExtra("activity", -1),
				new MyRequestCallBack<String>(this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								JSONArray result = json.getJSONArray("result");
								for (int i = 0; i < result.length(); i++) {
									BannerAdData data = new BannerAdData();
									JSONObject item = result.getJSONObject(i);
									data.setActivity_id(item
											.getInt("article_id"));
									data.setImg_url(item
											.getString("original_path"));
									bannerAdDatas.add(data);
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						bannerAdAdapter.notifyDataSetChanged();

					}
				});

	}

	/*
	 * 判断是否领取过
	 */
	protected void isJoinActivity() {
		if (!isLogin(false)) {
			if (detailData != null) {
				noLoginBotton();
			}
			return;
		}
		if (detailData != null) {
			httpUtils.send(
					HttpMethod.GET,
					HttpInterfaces.isJoinActivity + "&mobile="
							+ userData.getMobile() + "&password="
							+ userData.getPassword() + "&activity_id="
							+ detailData.getActivity_id() + "&type="
							+ detailData.getType(),
					new MyRequestCallBack<String>(this,
							getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
							TextView tv = (TextView) findViewById(R.id.get_type);
							tv.setEnabled(false);
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int status = json.getInt("status");
								TextView tv = (TextView) findViewById(R.id.get_type);
								tv.setTag(status);
								if (status == 1) {
									// 未参加
									tv.setEnabled(true);
									if (detailData != null
											&& detailData.getSurplus() <= 0) {
										tv.setEnabled(false);
										tv.setText("已领完");
									}
								} else if (status == 2) {
									// 已结生成兑换码 但是没有领取
									tv.setEnabled(true);
									tv.setText("领取");
									if (detailData != null
											&& detailData.getSurplus() <= 0) {
										tv.setEnabled(false);
										tv.setText("已领完");
									}
								} else if (status == -1) {
									// 已经参加
									tv.setEnabled(false);
									tv.setText("已领取");
								} else if (status == -5) {
									// 已过期
									tv.setEnabled(false);
									tv.setText("已过期");
								} else if (status == -100) {
									passwordIsError(false);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}

	}

	/*
	 * 未登录下的底部按钮
	 */
	private void noLoginBotton() {
		TextView tv = (TextView) findViewById(R.id.get_type);
		tv.setEnabled(true);
		tv.setText("登录");
		findViewById(R.id.botton_riqi_ll).setVisibility(View.GONE);
		((TextView) findViewById(R.id.syfs)).setText("总份数:");

		((TextView) findViewById(R.id.surplus))
				.setText((detailData.getNumber() > 0 ? detailData.getNumber()
						: 0) + "");

	}

	/*
	 * 分享领取 分享到商家规定的数目就可以领取
	 */
	protected void addSharedCount(final boolean isToResult) {
		if (!isLogin(false)) {
			return;
		}
		if (detailData != null) {
			httpUtils.send(
					HttpMethod.GET,
					HttpInterfaces.sharecount + "&mobile="
							+ userData.getMobile() + "&password="
							+ userData.getPassword() + "&activity_id="
							+ detailData.getActivity_id() + "&type="
							+ detailData.getType(),
					new MyRequestCallBack<String>(this,
							getString(R.string.loadding)) {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							if (isToResult) {
								try {
									JSONObject json = new JSONObject(
											responseInfo.result);
									int status = json.getInt("status");
									if (status == 1) {
										// 判断分享次数是否大于要求的次数
										int count = json.getInt("count");
										// 如果大于这调用分享领取接口
										if (detailData != null
												&& count >= detailData
														.getShare_count()) {
											// 跳转到结果界面
											Intent intent = new Intent();
											intent.putExtra("type",
													detailData.getType());
											intent.putExtra("activity_id",
													detailData.getActivity_id());
											intent.setClass(
													DetailActivity.this,
													ResultActivity.class);
											startActivity(intent);
										} else if (detailData != null
												&& count < detailData
														.getShare_count()) {
											int x = detailData.getShare_count()
													- count;
											if (x > 0) {
												// 对话框提示
												MyDialog dialog = new MyDialog(
														DetailActivity.this,
														R.style.base_dialog,
														MyDialog.MODE.CONFIRM);
												dialog.setContent("再分享" + x
														+ "次，可以领取兑换码啦");
												dialog.setConfirm("继续分享");
												dialog.setTitle("分享成功");
												dialog.setOnClickCallback(new OnClickCallback() {

													@Override
													public void onClick(
															MyDialog dialog,
															Object number,
															Object content) {
														if ((Integer) number == 2) {
															// 点击了确认按钮,再次分享
															shared(true);
														}

													}
												});
												dialog.show();
											}

										}
									} else if (status == -1) {

									} else if (status == -100) {
										passwordIsError(false);
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}

							}
						}
					});
		}

	}

	private void updataUi() {
		if (detailData != null) {
			if (detailData.getTitle() == null
					|| detailData.getTitle().trim().equals("")) {
				((TextView) findViewById(R.id.title)).setText("未知");
			} else {
				((TextView) findViewById(R.id.title)).setText(detailData
						.getTitle());
			}

			if (detailData.getTrade_name() == null
					|| detailData.getTrade_name().trim().equals("")) {
				((TextView) findViewById(R.id.shangjia)).setText("未知");
			} else {
				((TextView) findViewById(R.id.shangjia)).setText(detailData
						.getTrade_name());
			}

			((TextView) findViewById(R.id.fenshu)).setText((detailData
					.getNumber() > 0 ? detailData.getNumber() : 0) + "");

			((TextView) findViewById(R.id.syfs)).setText("剩余份数:");
			((TextView) findViewById(R.id.surplus)).setText((detailData
					.getSurplus() > 0 ? detailData.getSurplus() : 0) + "");
			((TextView) findViewById(R.id.renshu))
					.setText((detailData.getParticipation() > 0 ? detailData
							.getParticipation() : 0) + "");

			((TextView) findViewById(R.id.renshu))
					.setText((detailData.getParticipation() > 0 ? detailData
							.getParticipation() : 0) + "");

			if (detailData.getAddress() == null
					|| detailData.getAddress().trim().equals("")) {
				((TextView) findViewById(R.id.address)).setText("地址未知");
			} else {
				((TextView) findViewById(R.id.address)).setText(detailData
						.getAddress());
			}

			if (detailData.getTelephone() == null
					|| detailData.getTelephone().trim().equals("")) {
				((TextView) findViewById(R.id.phone)).setText("电话未知");
			} else {
				((TextView) findViewById(R.id.phone)).setText(detailData
						.getTelephone());
			}

			if (detailData.getContent() == null
					|| detailData.getContent().trim().equals("")) {
				upDateUI("暂无介绍");
			} else {
				upDateUI(detailData.getContent());
			}
			findViewById(R.id.botton_riqi_ll).setVisibility(View.VISIBLE);
			if (detailData.getContent() == null
					|| detailData.getContent().trim().equals("")) {
				((TextView) findViewById(R.id.endtime)).setText("未知");
			} else {
				((TextView) findViewById(R.id.endtime)).setText(detailData
						.getEnd_time());
			}
			if (detailData.getSurplus() > 0) {
				((TextView) findViewById(R.id.get_type)).setEnabled(true);
			} else {
				((TextView) findViewById(R.id.get_type)).setEnabled(false);
			}
		}
	}

	private void callPhone() {
		// 用intent启动拨打电话
		if (detailData.getTelephone() != null
				&& !detailData.getTelephone().trim().equals("")) {
			MyDialog dialog = new MyDialog(DetailActivity.this,
					R.style.base_dialog, MyDialog.MODE.CONFIRM);
			dialog.setContent(detailData.getTelephone().trim());
			dialog.setConfirm("呼叫");
			dialog.findViewById(R.id.title).setVisibility(View.GONE);
			dialog.setOnClickCallback(new OnClickCallback() {

				@Override
				public void onClick(MyDialog dialog, Object number,
						Object content) {
					if ((Integer) number == 2) {
						Intent intent = new Intent(Intent.ACTION_CALL, Uri
								.parse("tel:" + detailData.getTelephone()));
						startActivity(intent);
					}

				}
			});
			dialog.show();
		} else {
			MyToast.show(this, "暂不支持", Toast.LENGTH_SHORT);
		}
	}

	/*
	 * 当前是哪个兑换（type 0 1 2）
	 */
	private void switchUi(int type) {
		switch (type) {
		case 0:
			findViewById(R.id.botton_fenshu_rl).setVisibility(View.GONE);
			findViewById(R.id.view_temp).setVisibility(View.GONE);
			((TextView) findViewById(R.id.get_type)).setText("直接领取");
			break;
		case 1:
			findViewById(R.id.botton_fenshu_ll).setVisibility(View.GONE);
			((TextView) findViewById(R.id.get_type)).setText("分享领取");
			break;
		case 2:
			findViewById(R.id.botton_fenshu_ll).setVisibility(View.GONE);
			((TextView) findViewById(R.id.get_type)).setText("答题领取");
			break;

		default:
			break;
		}

	}

	/*
	 * 分享
	 */
	private void shared(final boolean isToResult) {
		if (detailData != null) {

			final StringBuilder imgUrl = new StringBuilder();
			String img = "";
			if (bannerAdDatas.size() > 0
					&& bannerAdDatas.get(0).getImg_url() != null
					&& !bannerAdDatas.get(0).getImg_url().trim().equals("")) {
				img = bannerAdDatas.get(0).getImg_url().trim();

			} else {
				img = detailData.getImg_url();
			}
			img = SystemTools.getHttpFileUrl(img);
			imgUrl.append(img);
			ShareSDK.initSDK(this);
			OnekeyShare oks = new OnekeyShare();
			// 关闭sso授权
			oks.disableSSOWhenAuthorize();
			// 参考代码配置章节，设置分享参数
			// 通过OneKeyShareCallback来修改不同平台分享的内容
			oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

				@Override
				public void onShare(Platform platform, ShareParams paramsToShare) {
					switch (platform.getName()) {
					case "QQ":
						paramsToShare.setTitle(detailData.getTitle());
						paramsToShare.setText(SystemTools.Html2Text(detailData
								.getContent()));
						paramsToShare
								.setTitleUrl("http://a.app.qq.com/o/simple.jsp?pkgname=com.hanbang.mrcm");
						paramsToShare.setImageUrl(imgUrl.toString());
						paramsToShare.setShareType(Platform.SHARE_WEBPAGE);

						break;
					case "QZone":
						paramsToShare.setTitle(detailData.getTitle());
						paramsToShare.setText(SystemTools.Html2Text(detailData
								.getContent()));
						paramsToShare
								.setTitleUrl("http://a.app.qq.com/o/simple.jsp?pkgname=com.hanbang.mrcm");
						paramsToShare.setImageUrl(imgUrl.toString());
						paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
						break;
					case "Wechat":
					case "WechatFavorite":
					case "WechatMoments":
						paramsToShare.setTitle(detailData.getTitle());
						paramsToShare.setText(SystemTools.Html2Text(detailData
								.getContent()));
						paramsToShare.setImageUrl(imgUrl.toString());
						paramsToShare
								.setUrl("http://a.app.qq.com/o/simple.jsp?pkgname=com.hanbang.mrcm");
						paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
						break;

					default:
						break;
					}

				}
			});
			MyLog.e("sssss", SystemTools.Html2Text(detailData.getContent()));
			oks.setCallback(new PlatformActionListener() {

				@Override
				public void onError(Platform arg0, int arg1, Throwable arg2) {
					MyLog.e("PlatformActionListener", "onError   " + arg1);
					MyToast.show(DetailActivity.this, "分享失败",
							Toast.LENGTH_SHORT);
				}

				@Override
				public void onComplete(Platform arg0, int arg1,
						HashMap<String, Object> arg2) {
					shareComplete(isToResult);
					MyLog.e("PlatformActionListener", "onComplete   " + arg1
							+ "    " + arg2.toString());
				}

				@Override
				public void onCancel(Platform arg0, int arg1) {
					MyLog.e("PlatformActionListener", "onCancel   " + arg1);
				}
			});
			oks.show(this);
		}
	}

	/*
	 * 分享完成
	 */
	private void shareComplete(boolean isToResult) {
		MyToast.show(this, "分享成功", Toast.LENGTH_SHORT);
		if (userData != null) {
			if (detailData != null)
				if (detailData.getType() == 1) {
					// 是分享领取类型 分享后要提交
					addSharedCount(isToResult);
				}
		}
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void configWebview() {
		// 设置文本编码
		webview.getSettings().setDefaultTextEncodingName("utf-8");
		// 可以缩放
		webview.getSettings().setSupportZoom(true);
		webview.getSettings().setJavaScriptEnabled(true);
		webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		// 开启 Application Caches 功能
		webview.getSettings().setAppCacheEnabled(false);
		webview.getSettings().setLoadWithOverviewMode(true);
		// webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);// 默认缩放模式
		webview.getSettings().setUseWideViewPort(false);
	}

	/*
	 * 获取到服务器数据后开始跟新UI
	 */
	private void upDateUI(String content) {
		// 配置webview数据源
		StringBuilder data = new StringBuilder();
		data.append("<style type=\"text/css\">img{WIDTH:80% !important;HEIGHT:auto !important;}");
		data.append(getFont());
		data.append("</style><base href=\"");
		data.append(HttpInterfaces.ORG);
		data.append("\"/><body class=\"Likun\" style=\"padding-left:2%;padding-right:2%;\">");
		data.append(content);
		data.append("</body>");
		MyLog.e("upDateUI", data.toString());

		// 设置webview 加载数据
		webview.loadDataWithBaseURL(null, data.toString(), "text/html",
				"utf-8", null);
	}

	private String getFont() {
		StringBuilder builder = new StringBuilder();
		// <body class="MsoNormal"> </body>
		builder.append(".Likun { font-family: fzlt;}");
		builder.append("@font-face {font-family:fzlt;");
		builder.append("src:url(file:///android_asset/fzlt.ttf);}");
		return builder.toString();
	}

	@Override
	protected void onResume() {
		super.onResume();
		updataUi();
		isJoinActivity();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
